/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.dtd.implementation;

import com.dtd.structure.IConnector;
import java.net.MalformedURLException;
import java.util.Map;

import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

/**
 *
 * @author TQD
 */
public class Connector implements IConnector {

    @Override
    // Login to CMS
    public Map<String, String> getCookies(String username, String password) {
        Map<String, String> cookies = null;
        try {
            Connection.Response response = Jsoup.connect("http://cms-hcm.fpt.edu.vn/elearning/login/index.php")
                    .data("username", username)
                    .data("password", password)
                    .timeout(30 * 1000)
                    .method(Connection.Method.POST)
                    .execute();
            if (response.url().toString().equals("http://cms-hcm.fpt.edu.vn/elearning/login/index.php")) {
                return null;
            }
            cookies = response.cookies();
        } catch (MalformedURLException e) {
            System.out.println(e.getMessage());
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        return cookies;
    }

    @Override
    // lấy tên các môn học, categories trên elearning 
    public Document getDocument(Map<String, String> cookies) {
        try {
            return Jsoup.connect("http://cms-hcm.fpt.edu.vn/elearning/").timeout(30 * 1000).cookies(cookies).get();
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        return null;
    }

    @Override
    //đăng nhập theo id của môn học
    public Connection.Response getResponseForCourse(Map<String, String> cookies, String id) {
        Connection.Response response = null;
        try {
            String url = "http://cms-hcm.fpt.edu.vn/elearning/course/view.php?id=" + id;
            response = Jsoup.connect(url).timeout(30 * 1000)
                    .cookies(cookies).execute();
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        return response;
    }
    
    //Quan
    @Override
    // get document 1 page
    public Document getAttDocument(Map<String, String> cookies, String url) {
        try { 
            return Jsoup.connect(url).timeout(30 * 1000).cookies(cookies).get();
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        return null;
    }
}
